import { createSlice } from '@reduxjs/toolkit'
const userSlice = createSlice({
	name: 'user',
	initialState: {
		user: null,
	},
	// reducers: 同步方法
	reducers: {
		setUser: (state, action) => {
			state.user = action.payload
		},
	},
})

const { setUser } = userSlice.actions
const URL = import.meta.env.VITE_API_URL
const login = (user: any) => {
	console.log(user)
	return async (dispatch: any) => {
		// 异步请求
		try {
			const res = await fetch(`${URL}/admin/login`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify(user),
			})
			const data = await res.json()
			if (data.code === 0) {
				// 成功
				dispatch(setUser(data.data.realName))
			} else {
				throw data.msg
			}
		} catch (error) {
			throw error
		}
	}
}
export { login }
export default userSlice.reducer
